package  com.diamond.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.struts2.ServletActionContext;

import com.diamond.bo.DiamondBO;
import com.diamond.bo.ExcelUtils3;
import com.diamond.bo.QueryDiamondBO;
import com.diamond.bo.ReturnBO;
import com.diamond.bo.SDiamondBO;
import com.diamond.facade.DiamondFacade;
import com.diamond.util.DeleteFileUtil;
import com.diamond.util.JsonMSG;
import com.diamond.util.JsonUtils;
import com.diamond.util.StringUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unchecked")
public class DiamondAction extends ActionSupport {

	private static final long serialVersionUID = -1437304228291293863L;
	private HttpServletRequest request = ServletActionContext.getRequest();
	private DiamondFacade diamondFacade;
	private DiamondBO diaBo;;
	private SDiamondBO sDiamondBo;
	private QueryDiamondBO queryDiamondBo;
	private List<DiamondBO> dataList;
//	private ExcelForm excelForm;
//	private File excelFile;
	private File excelFile;
	private String fileFileName;
	private String json;
	
	/**
	 * 跳转普通钻石查询页面
	 * @return
	 */
	public String toDiamond(){
		String url="todiamond.action?a=1";
		Map session = ActionContext.getContext().getSession();
		if("B".equals(session.get("USER_TYPE"))){
			dataList = diamondFacade.getSaleCost(ServletActionContext.getRequest(),ActionContext.getContext().getSession(),url,sDiamondBo);
		}else{
			dataList = diamondFacade.getSale(ServletActionContext.getRequest(),ActionContext.getContext().getSession(),url,sDiamondBo);
		}
		return SUCCESS;
	}
	
	
	/**
	 * 跳转成本价钻石查询页面
	 * @return
	 */
	public String toCostDia(){
		String url="tocostdia.action?a=1";
		Map session = ActionContext.getContext().getSession();
		if("B".equals(session.get("USER_TYPE"))){
			dataList = diamondFacade.getAngentCost(ServletActionContext.getRequest(),ActionContext.getContext().getSession(),url,sDiamondBo);
		}else{
			dataList = diamondFacade.getSaleCost(ServletActionContext.getRequest(),ActionContext.getContext().getSession(),url,sDiamondBo);
		}
		return SUCCESS;
	}
	
	/**
	 * 跳转特价钻石查询页面
	 * @return
	 */
	public String toSpeDia(){
		String url="tospedia.action?a=1";
		dataList =diamondFacade.getSpe(ServletActionContext.getRequest(),ActionContext.getContext().getSession(),url,sDiamondBo);
		return SUCCESS;
	}
	
	/**
	 * 跳转到钻石明细页面
	 * @return
	 */
	public String toDiaDetail(){
		String id=ServletActionContext.getRequest().getParameter("diamondid");
		if(!StringUtils.isEmpty(id)){
			Long userId=(Long) ActionContext.getContext().getSession().get("USER_ID");
			diaBo=diamondFacade.findDiaById(Long.parseLong(id),userId);
		}
		return SUCCESS;
	}
	/**
	 * 跳转到成本价钻石明细页面
	 * @return
	 */
	public String toMidDiaDetail(){
		String id=ServletActionContext.getRequest().getParameter("diamondid");
		if(!StringUtils.isEmpty(id)){
			Long userId=(Long) ActionContext.getContext().getSession().get("USER_ID");
			diaBo=diamondFacade.findMidDiaById(Long.parseLong(id),userId);
		}
		return SUCCESS;
	}
	
/** **************************************************************************************/
	public String queryDiamond() {
//		System.out.println("**************后台钻石查询***************");
		request = ServletActionContext.getRequest();
		String start = request.getParameter("start");
		String pageSize = request.getParameter("limit");
		if(null==json|| "".equals(json.trim())||"null".equals(json.toLowerCase())){//默认查询全部;
			queryDiamondBo=new QueryDiamondBO();
		}
		else{
			queryDiamondBo=(QueryDiamondBO) JsonUtils.toObject(json, QueryDiamondBO.class);
		}
		if (null == start || "".equals(start) || null == pageSize || "".equals(pageSize)) {
			if ("Y".equals(queryDiamondBo.getDownloadAllData())) {
				queryDiamondBo.setStart(0);
				queryDiamondBo.setPageSize(6000);
			}else {
				queryDiamondBo.setStart(0);
				queryDiamondBo.setPageSize(100);
			}
		} else {
			queryDiamondBo.setStart(Integer.valueOf(start));
			queryDiamondBo.setPageSize(Integer.valueOf(pageSize));
		}
//		queryDiamondBo=(QueryDiamondBO) JsonUtils.toObject(json, QueryDiamondBO.class);
		Map session = ActionContext.getContext().getSession(); 
	    Object obj=session.get("USER_ID");
	    if(obj==null) {
	    	this.json = JsonMSG.failed("查询失败，请您先登录！").toString();
	    } else {
	    	Long id=(Long) obj;
	    	sDiamondBo = new SDiamondBO();
//	    	String[] weights = {queryDiamondBo.getWeightFrom(), queryDiamondBo.getWeightTo()}; 
	    	sDiamondBo.setMinWeight(queryDiamondBo.getWeightFrom());
	    	sDiamondBo.setMaxWeight(queryDiamondBo.getWeightTo());
	    	sDiamondBo.setMinPrice(queryDiamondBo.getPriceFrom());
	    	sDiamondBo.setMaxPrice(queryDiamondBo.getPriceTo());
	    	if (!StringUtil.isEmpty(queryDiamondBo.getBuffing()))
	    		sDiamondBo.setBuffing(queryDiamondBo.getBuffing().replace('|', ';').split(";"));
	    	if (!StringUtil.isEmpty(queryDiamondBo.getCerificate()))
	    		sDiamondBo.setCerificate(queryDiamondBo.getCerificate().replace('|', ';').split(";"));
	    	if (!StringUtil.isEmpty(queryDiamondBo.getColour()))
	    		sDiamondBo.setColour(queryDiamondBo.getColour().replace('|', ';').split(";"));
	    	if (!StringUtil.isEmpty(queryDiamondBo.getCutter()))
	    		sDiamondBo.setCutter(queryDiamondBo.getCutter().replace('|', ';').split(";"));
	    	if (!StringUtil.isEmpty(queryDiamondBo.getFluorescence()))
	    		sDiamondBo.setFluorescence(queryDiamondBo.getFluorescence().replace('|', ';').split(";"));
	    	if (!StringUtil.isEmpty(queryDiamondBo.getPurity()))
	    		sDiamondBo.setPurity(queryDiamondBo.getPurity().replace('|', ';').split(";"));
	    	if (!StringUtil.isEmpty(queryDiamondBo.getSymmetry()))
	    		sDiamondBo.setSymmetry(queryDiamondBo.getSymmetry().replace('|', ';').split(";"));
	    	sDiamondBo.setStart(queryDiamondBo.getStart());
	    	sDiamondBo.setPageSize(queryDiamondBo.getPageSize());
//	    	dataList = diamondFacade.getCost(ServletActionContext.getRequest(),null,sDiamondBo);
	    	ReturnBO<DiamondBO> returnBo = diamondFacade.getBackCost(request, null, sDiamondBo);
	    	this.json=JsonMSG.sucess(returnBo).toJson();
	    }
		return "json";
	}
	
	public String uploadExcel() {
//		System.out.println("*******************uploadExcel()*************************");
//		System.out.println(excelFile);
		request = ServletActionContext.getRequest();
		String uploadType = request.getParameter("uploadType");
		try {
			String persistFileName = getFileName(excelFile.getName());
			InputStream is = new FileInputStream(excelFile);
			File persistFile = new File(persistFileName);
			persistFile.createNewFile();
			FileOutputStream out = new FileOutputStream(persistFile);
			byte[] by = new byte[500];
			while (is.read(by) > -1) {
				out.write(by);
			}
			out.close();
			is.close();
			// 由Session中得到Excel
			Workbook workbook = Workbook.getWorkbook(new FileInputStream(excelFile));
			// 验证;
			ExcelUtils3 utils = new ExcelUtils3();
			Sheet[] sheets = workbook.getSheets();
			List<DiamondBO> list = new ArrayList<DiamondBO>();
//			Map<String, List<DiamondBO>> map = new HashMap<String, List<DiamondBO>>();
			for (Sheet sh : sheets) {
				list = utils.convertSheetToList(sh);// 直接转换成了对象列表;
				if (list.size() > 0) {
					diamondFacade.saveOrUpdate(list, uploadType);
				}
			}
			DeleteFileUtil.delete(persistFileName);  
			this.json = JsonMSG.sucess("上传成功！").toJson();
		} catch (Exception e) {
			e.printStackTrace();
			this.json = JsonMSG.failed("上传失败！").toJson();
		}
		return "json";
	}
	
	public String getFileName(String oldName) {
		if (oldName == null || oldName.trim().equals("")) {
			throw new java.lang.NullPointerException();
		}
		int index = oldName.lastIndexOf(".");

		String suffix = index > 0 ? oldName.substring(index) : ".tmp";
		int ran = RandomUtils.nextInt(10000);
		return "D:/DOC/" + (new Date()).getTime() + ran + suffix;
	}

	public void setDiamondFacade(DiamondFacade diamondFacade) {
		this.diamondFacade = diamondFacade;
	}
    	
	
	public DiamondBO getDiaBo() {
		return diaBo;
	}

	public void setDiaBo(DiamondBO diaBo) {
		this.diaBo = diaBo;
	}

	public List<DiamondBO> getDataList() {
		return dataList;
	}

	public void setDataList(List<DiamondBO> dataList) {
		this.dataList = dataList;
	}

	public SDiamondBO getsDiamondBo() {
		return sDiamondBo;
	}

	public void setsDiamondBo(SDiamondBO sDiamondBo) {
		this.sDiamondBo = sDiamondBo;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public SDiamondBO getSDiamondBo() {
		return sDiamondBo;
	}

	public void setSDiamondBo(SDiamondBO diamondBo) {
		sDiamondBo = diamondBo;
	}

	public QueryDiamondBO getQueryDiamondBo() {
		return queryDiamondBo;
	}

	public void setQueryDiamondBo(QueryDiamondBO queryDiamondBo) {
		this.queryDiamondBo = queryDiamondBo;
	}

	public File getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(File excelFile) {
		this.excelFile = excelFile;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	
}
